import { provide, Ref, ref, watch } from 'vue'

interface ModalToParams {
  title: string
  haveBackIcon?: boolean
  [key: string]: any
}

export function useModalContext(options: {
  uid: string
  onStackChange?: (currentStackFrame: Ref<number>, modalContentStack: Ref<ModalToParams[]>) => void
}) {
  // 当前弹窗内容栈帧
  const currentStackFrame = ref(0)
  // 弹窗内容堆栈
  const modalContentStack = ref<ModalToParams[]>([
    {
      title: '',
      haveBackIcon: false
    }
  ])

  // 组件远程注入弹窗内容堆栈
  provide(options.uid, modalContentStack)

  // 回退弹窗内容栈帧
  const backStack = () => {
    modalContentStack.value.pop()
    currentStackFrame.value--
  }

  // 去到指定弹窗内容栈帧
  const toStack = (stackFrame: number, params: ModalToParams) => {
    if (currentStackFrame.value < stackFrame) {
      for (let i = 0; i < stackFrame - currentStackFrame.value; i++) {
        modalContentStack.value.push({
          ...params,
          haveBackIcon: true
        })
      }
      currentStackFrame.value = stackFrame
      return
    }
    if (currentStackFrame.value > stackFrame) {
      for (let i = 0; i < currentStackFrame.value - stackFrame; i++) {
        modalContentStack.value.pop()
      }
      modalContentStack.value.splice(stackFrame, 1, params)
      if (stackFrame === 0) {
        modalContentStack.value[stackFrame].haveBackIcon = false
      }
      currentStackFrame.value = stackFrame
      return
    }
    if (currentStackFrame.value === stackFrame) {
      modalContentStack.value.splice(stackFrame, 1, params)
      return
    }
  }

  // 下一个弹窗内容栈帧
  const pushStack = (params: ModalToParams) => {
    modalContentStack.value.push({
      ...params,
      haveBackIcon: true
    })
    currentStackFrame.value++
  }

  watch([modalContentStack, currentStackFrame], () => {
    if (!!options.onStackChange) {
      options.onStackChange(currentStackFrame, modalContentStack)
    }
  })

  return {
    currentStackFrame,
    modalContentStack,
    backStack,
    toStack,
    pushStack
  }
}
